package com.brook.app.android.filepickertest;

import android.app.Application;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.widget.ImageView;

import com.brook.app.android.filepicker.core.FilePickerConfig;
import com.brook.app.android.filepicker.core.FilePickerConfigRegistry;
import com.brook.app.android.filepicker.core.IThumbnailLoader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.io.File;

public class App extends Application {


    @Override
    public void onCreate() {
        super.onCreate();

        FilePickerConfig defaultConfig = FilePickerConfigRegistry.getDefaultConfig();
        defaultConfig.setImageLoader(new IThumbnailLoader() {

            final RequestOptions requestOptions =
                    new RequestOptions()
                            .centerCrop()
                            .placeholder(R.drawable.ic_empty);

            @Override
            public void loadThumbnail(File sourceFile, ImageView previewImageView) {
                // 如果需要加载其他的类型的图片，预览图策略需要更改，以便显示预览图或者图标
                if (isImageType(sourceFile)) {
                    Glide.with(previewImageView.getContext())
                            .load(sourceFile)
                            .apply(requestOptions)
                            .into(previewImageView);
                } else if (isVideoType(sourceFile)) {
                    MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
                    metadataRetriever.setDataSource(sourceFile.getAbsolutePath());
                    Bitmap frame = metadataRetriever.getFrameAtTime();

                    previewImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    previewImageView.setImageBitmap(frame);
                }

            }

            private boolean isVideoType(File sourceFile) {
                return sourceFile.exists() && sourceFile.getAbsolutePath().endsWith(".mp4");
            }

            private boolean isImageType(File sourceFile) {
                return sourceFile.exists()
                        && (sourceFile.getAbsolutePath().endsWith(".jpg")
                        || sourceFile.getAbsolutePath().endsWith(".jpeg")
                        || sourceFile.getAbsolutePath().endsWith(".png")
                        || sourceFile.getAbsolutePath().endsWith(".JPEG")
                        || sourceFile.getAbsolutePath().endsWith(".PNG"));
            }
        });
        defaultConfig.setApplicationContext(this);
        defaultConfig.setPickCount(20);
    }
}
